package flex.cc.uac.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import flex.cc.PublicUtil;
import flex.cc.RedisKeyUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.common.utils.JwtUtils;
import flex.cc.e2.service.E2LoginService;
import flex.cc.uac.entity.UacActionEntity;
import flex.cc.uac.entity.UacMenuEntity;
import flex.cc.uac.entity.UacUserEntity;
import flex.cc.uac.service.UacActionService;
import flex.cc.uac.service.UacMenuService;
import flex.cc.uac.service.UacUserService;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;

@RestController
public class LoginController {

    @Autowired
    private UacUserService uacUserService;

    @Autowired
    private UacMenuService uacMenuService;

    @Autowired
    private UacActionService uacActionService;

    @Autowired
    private E2LoginService e2LoginService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private JwtUtils jwtUtils;

    @Value("${sso.tokenHead:WebType }")
    private String tokenHead;

    @RequestMapping(value = "/auth/login", method = RequestMethod.POST)
    public Wrapper<Object> login(@RequestParam(value = "userCode") String userCode,
                                 @RequestParam(value = "password") String password, HttpServletRequest request){
        String result = null;
        UacUserEntity uacUserEntity = uacUserService.findByLoginName(userCode);
//        uacUserEntity = uacUserService.findUserInfoByUserId(uacUserEntity.getId());
        if(!PublicUtil.isEmpty(uacUserEntity)){
            String loginPwq = uacUserEntity.getLoginPwd();
            if(password.equals(loginPwq)){
                Map<String,Object> claims = new HashMap<>();
                claims.put("userCode",uacUserEntity.getUserCode());
                claims.put("userName",uacUserEntity.getUserName());
                claims.put("belongComCode",uacUserEntity.getBelongComCode());
                claims.put("comCode", uacUserEntity.getBelongComCode());
                String token = jwtUtils.generateHS256JwtHasExpiration(claims);
                token = StringUtils.substringAfter(token,tokenHead);
                Map<String,String> data = new HashMap<>();
                data.put("token", token);
                data.put("userId", uacUserEntity.getId()+"");
                data.put("userCode",uacUserEntity.getUserCode());
                data.put("userName",uacUserEntity.getUserName());
                data.put("belongComCode",uacUserEntity.getBelongComCode());
                data.put("belongComName",uacUserEntity.getBelongComName());
                data.put("comCode",uacUserEntity.getBelongComCode());
                data.put("comName", uacUserEntity.getBelongComName());
                uacUserService.handlerLoginData(token,data,request);
                return WrapMapper.ok(data);
            }else{
                result = "用户名或密码错误";
                return WrapMapper.error(result);
            }
        }else{
            result = "用户名或密码错误";
            return WrapMapper.error(result);
        }
    }


    @PostMapping("/auth/code/image")
    public void generateImageCode(@RequestHeader(value="deviceId") String deviceId){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        System.out.println(deviceId);
    }

    @GetMapping("/auth/user/info")
    public Wrapper<Map<String,Object>> userInfo(@RequestParam String token, HttpServletRequest request){

        LoginAuthDto loginAuthDto = (LoginAuthDto) redisTemplate.opsForValue().get(RedisKeyUtil.getAccessTokenKey(token));

        /** 统一登录对接，如果本地取token缓存为空的话，则调用e2接口调取登录信息，存入本地 */
        if(loginAuthDto == null) {
        	// 添加本地缓存
        	String cacheUserMsg = e2LoginService.cacheUserInfoFromE2(request);
        	if("ok".equals(cacheUserMsg)) {
        		loginAuthDto = (LoginAuthDto) redisTemplate.opsForValue().get(RedisKeyUtil.getAccessTokenKey(token));
        	} else {
        		return WrapMapper.error(cacheUserMsg);
        	}
        }

        System.out.println(loginAuthDto);
        Map<String,Object> map = new HashMap<>();
        ArrayList<String> list = new ArrayList<>();
        list.add("admin");
        map.put("roles", list);
        map.put("introduction","I am a super administrator");
        map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name",loginAuthDto.getUserName());
        map.put("userCode",loginAuthDto.getUserCode());
        map.put("comCode",loginAuthDto.getComCode());

        List<UacMenuEntity> menuList = uacMenuService.getMenuList(loginAuthDto.getUserId(), null);
        List<UacActionEntity> actionList = uacActionService.getOwnActionListByUserId(loginAuthDto.getUserId());
        List<String> authList = Lists.newArrayList();
        for (UacActionEntity action : actionList) {
            authList.add(action.getActionCode());
        }
        map.put("menuList",menuList);
        map.put("actionList",authList);
        return WrapMapper.ok(map);
    }

    @PostMapping("/auth/user/logout")
    public Wrapper<Map<String,Object>> userLogout(){
        return WrapMapper.ok();
    }

}
